#!/bin/sh

STATUS=true

echo '\033[0;33;1m1-get APT source update...\033[0m'
apt-get update | tee install.log
if [ $? -eq 0 ];
then echo '\033[0;33;1m1DONE!\033[0m';
fi
echo '\033[0;33;1m...\033[0m'
echo '\033[0;33;1m2-dist upgrade...\033[0m'
apt-get dist-upgrade -y | tee -a install.log
if [ $? -eq 0 ];
then echo '\033[0;33;1m2DONE!\033[0m';
fi
echo '\033[0;33;1m...\033[0m'
echo '\033[0;33;1m3-install nginx mysql php and spawn-fcgi...\033[0m'
apt-get install -y mysql-server mysql-client php5-cgi php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-common php5-ming php5-ps php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl nginx spawn-fcgi | tee -a install.log
if [ $? -eq 0 ];
then echo '\033[0;33;1m3DONE!\033[0m';
fi
echo '\033[0;33;1m...\033[0m'
echo '\033[0;33;1m4-configing php.ini...\033[0m'
echo cgi.fix_pathinfo=1 >> /etc/php5/cgi/php.ini | tee -a install.log
if [ $? -eq 0 ];
then echo '\033[0;33;1m4DONE!\033[0m';
fi
echo '\033[0;33;1m...\033[0m'
echo '\033[0;33;1m5-touch /etc/init.d/php5-cgi...\033[0m'

##########touch php5-cgi##########
cat << EOF > /etc/init.d/php5-cgi
#! /bin/sh

### BEGIN INIT INFO
# Provides:          php5-cgi
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the php5-cgi
# Description:       starts php5-cgi using spawn-fcgi
### END INIT INFO

PATH=/usr/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin
DAEMON=/usr/bin/php5-cgi
NAME=php5-cgi
DESC=php5-cgi
PORT=9000
USER=www-data
CHILD=9
test -x $DAEMON || exit 0

# Include php5-cgi defaults if available
if [ -f /etc/default/nginx ] ; then
        . /etc/default/nginx
fi

set -e

. /lib/lsb/init-functions

case "$1" in
  start)
        echo -n "Starting $DESC: "
        spawn-fcgi -a 127.0.0.1 -p $PORT -u $USER -g $USER -f $DAEMON -P /var/run/$NAME.pid -C $CHILD || true
        ;;
  stop)
        echo -n "Stopping $DESC: "
        killall $NAME || true
        ;;
  restart|force-reload)
        echo -n "Restarting $DESC: "
        killall $NAME || true
        sleep 1
        spawn-fcgi -a 127.0.0.1 -p $PORT -u $USER -g $USER -f $DAEMON -P /var/run/$NAME.pid -C $CHILD || true
        ;;
  status)
        status_of_proc -p /var/run/$NAME.pid "$DAEMON" php5-cgi && exit 0 || exit $?
        ;;
  *)
        echo "Usage: $NAME {start|stop|restart|status}" >&2
        exit 1
        ;;
esac

exit 0
EOF
##########touch php5-cgi end##########
chmod +x /etc/init.d/php5-cgi -v | tee -a install.log
if [ $? -eq 0 ];
then echo '\033[0;33;1m5DONE!\033[0m';
fi
echo '\033[0;33;1m...\033[0m'
echo '\033[0;33;1m6-autostart php5-cgi...\033[0m'
update-rc.d php5-cgi defaults | tee -a install.log
if [ $? -eq 0 ];
then echo '\033[0;33;1m6DONE!\033[0m';
fi
echo '\033[0;33;1m...\033[0m'
echo '\033[0;33;1mALL DONE! PLEASE CHECK THE INSTALL LOG.\033[0m'
